/**
 * <p>treepanel的控制类</p>
 * 继承自Ext.app.Controller

 * @module Ext-ux-cceaf-controller
 * @class cceaf.controller.TreePanelCtrl
 * @extends Ext.app.Controller
 * @since 1.0
 */
Ext.define('cceaf.controller.TreePanelCtrl',{
	extend: 'Ext.app.Controller', 
	requires: [
	    
    ],
	
	
    constructor: function(config){
		config = config || {};
		
		config = Ext.applyIf(config || {}, {

		});

		cceaf.controller.TreePanelCtrl.superclass.constructor.apply(this, arguments);
	},

	/**
     * 监听事件
     */
    init: function() {
    	//控制层需控制视图的xtype
    	var controlledViewXType = this.controlledViewXType;
    	if (!controlledViewXType) {
    		//控制名称
    		var className = this.self.getName();
    		alert('必须设置控制层' + className + '需控制视图的xtype，即controlledViewXType属性！');
    		return;
    	}
    	
    	//构建初始化的事件监听
    	var eventTemplate = "this.control({" + 
	    	"'aaaaa': {" +
	    	"	afterrender: this.initPage" +
	        "}," +
	        "'aaaaa': {" +
	    	"	itemcontextmenu: this.showContextMenu" +
	        "}" +
    	"});";
	    
	    var eventString = eventTemplate.replace(/aaaaa/gi, controlledViewXType);
	    eval(eventString);
        
        this.registerEvent();
        
        //标记已经初始化完成
        this.isInit = true;
    },
    
    /**
     * 对于动态加载controller模式
     * 第一次加载后设置为true，再次加载后不在执行init方法 
     * 
     * @property isInit 
     * @type Boolean
     * @default false
     */
    isInit: false,
    
    /**
     * 显示右键点击树节点的
     */
    showContextMenu: function(view,record,item,index,e){
    	var controller = this;
    	var treePanel = controller.getControlledView();

    	//如果树型控件没有设置contextMenu，给定默认弹出菜单
    	var contextMenu = treePanel.contextMenu;
		if (contextMenu == null) {
			contextMenu = new Ext.menu.Menu( {
				width: 100,
				items : [ {
					text : '新增' + treePanel.moduleName,
					iconCls : 'page_addIcon',
					handler : function() {
						controller.page_add();
					}
				}, {
					text : '查看' + treePanel.moduleName,
					iconCls : 'page_viewIcon',
					handler : function() {
						controller.page_view();
					}
				}, {
					text : '修改' + treePanel.moduleName,
					iconCls : 'page_editIcon',
					handler : function() {
						controller.page_edit();
					}
				}, {
					text : '删除' + treePanel.moduleName,
					iconCls : 'page_deleteIcon',
					handler : function() {
						controller.page_delete();
					}
				}, {
					xtype : 'menuseparator'
				}, {
					text : '刷新' + treePanel.moduleName,
					iconCls : 'page_refreshIcon',
					handler : function() {
						var treePanel = controller.getControlledView();
						treePanel.getStore().load();
					}
				}]
			});
		}
		
		e.preventDefault();
		//显示popmenu
		contextMenu.showAt(e.getXY());
    },
    
    /**
     * 监听其他事件
     */
    registerEvent: function(){
    	
    },
	
    /**
	 * 获取视图
	 *
     * @return {Ext.container.Container} 视图对象
     */
    getControlledView: function(){
    	var controlledViewXType = this.controlledViewXType;
    	var methodName = 'this.get' + controlledViewXType.substr(0,1).toUpperCase() + controlledViewXType.substring(1) + '()';
    	//alert(methodName);
    	
    	var view = eval(methodName);
    	return view;
    },
    
    /**
     * 新增对象
     */
    page_add: function(){
    	var controller = this;
    	var treePanel = controller.getControlledView();
    	
    	var popWindow = treePanel.popWindow;
		var popWindowWidth = popWindow.width;
		var popWindowHeight = popWindow.height;
		
		if (controller.checkAddPage() == false) {
			return;
		}
    	
    	//设置页面状态为：新增页面
		treePanel.pageStatus = 'add';
    	var title = '新增' + treePanel.moduleName;
    	
    	//var billForm = treePanel.billForm;
    	if(treePanel.newFormCreate == true || treePanel.billForm == null){
    		treePanel.createForm();
    	}
	    	
    	treePanel.billForm.form.reset();
    	treePanel.billForm.setReadOnly(false);
    	
		var btnSave = treePanel.billForm.down('[itemId=btnSave]');
		if (btnSave) {
			btnSave.setVisible(true);
		}
		
		//设置父节点值
		var selModel = treePanel.getSelectionModel();
		var selectedCount = selModel.getCount();
    	if(selectedCount == 0){
    		cceaf.util.ExtHelper.showInfoDialog('请选择父节点');
    		return;
    	}
    	else{
    		var nodeid = selModel.getLastSelected().get('id');
    		var nodename = selModel.getLastSelected().get('text');
    		
    		var parentId = treePanel.billForm.down('[name=' + treePanel.parentId + ']');
    		if (parentId) {
    			parentId.setValue(nodeid);
        		parentId.setRawValue(nodename);
    		} 
    		
    		var parentName = treePanel.billForm.down('[name=' + treePanel.parentName + ']');
    		if (parentName) {
    			parentName.setValue(nodename);
    		}
    	}
    	
		new Ext.Window({
        	title: title,
        	modal: true,
        	width: popWindowWidth,
        	height: popWindowHeight,
        	autoScroll: true,
        	layout: 'fit',
        	plain: true,
        	closeAction: 'hide', //可能会造成内存泄漏，但如果不用hide会出错，估计是extjs的bug
        	items: [treePanel.billForm]
    	}).show();
		
    	//设置初始值
    	controller.initAddPage();
    },
    
    /**
     * 编辑对象
     */
    page_edit: function(){
    	var controller = this;
    	var treePanel = controller.getControlledView();
    	
    	var popWindow = treePanel.popWindow;
		var popWindowWidth = popWindow.width;
		var popWindowHeight = popWindow.height;
		
    	var selModel = treePanel.getSelectionModel();
    	
    	//设置页面状态为：编辑页面
    	treePanel.pageStatus = 'edit';
    	var title = '编辑' + treePanel.moduleName;
    	
   	 	var selectedCount = selModel.getCount();
    	if(selectedCount == 0){
    		cceaf.util.ExtHelper.showInfoDialog('请选择编辑的行');
    		return;
    	}
    	else if(selectedCount > 1){
    		cceaf.util.ExtHelper.showInfoDialog('只能选择一行编辑');
    		return;
    	}
    	else{
    		//得到编辑对象的主键
    		var masterkeys = treePanel.masterKeyIds.split(',');
    		var url = treePanel.findByKeyAction + '?';
    		var temp = selModel.getLastSelected().get(treePanel.modelKey);
    		url += masterkeys[0] + '=' + temp + '&';

	    	if(treePanel.newFormCreate == true || treePanel.billForm == null){
	    		treePanel.createForm();
	    	}
	    	
			treePanel.billForm.form.reset();
			treePanel.billForm.setReadOnly(false);
			
			var btnSave = treePanel.billForm.down('[itemId=btnSave]');
			if (btnSave) {
				btnSave.setVisible(true);
			}
			
    		new Ext.Window({
	        	title: title,
	        	modal: true,
	        	width: popWindowWidth,
	        	height: popWindowHeight,
	        	autoScroll:true,
	        	closeAction: 'hide',
	        	layout: 'fit',
	        	items: [treePanel.billForm]
		    }).show();
        	
        	//装载对象到表单
        	treePanel.billForm.form.load({
		    	//url: treePanel.findByKeyAction + '?' + treePanel.masterKeyId + '=' + masterkey,
        		url:  url,
		        waitMsg : '正在载入数据...',
		        success: function(form,action) { 
		        	//表单载入数据时,初始化其他操作	        	
		        	controller.initEditPage(action);
		        	
		        	//显示正确提示
		        	var jsonObject =eval("(" + action.response.responseText + ")");
		        	cceaf.util.ExtHelper.showInfoDialog(jsonObject.message);
		        },
		        failure: function(form,action) {
		        	//显示错误提示
		        	var jsonObject =eval("(" + action.response.responseText + ")");
		        	cceaf.util.ExtHelper.showErrorDialog(jsonObject.message);
		        }
		   	});
    	}
    },
    
    /**
     * 查看对象
     */
    page_view: function(){
    	var controller = this;
    	var treePanel = controller.getControlledView();
    	
    	var popWindow = treePanel.popWindow;
		var popWindowWidth = popWindow.width;
		var popWindowHeight = popWindow.height;
    	
    	var selModel = treePanel.getSelectionModel();
    	
    	//设置页面状态为：编辑页面
    	treePanel.pageStatus = 'view';
    	var title = '查看' + treePanel.moduleName;
    	
   	 	var selectedCount = selModel.getCount();
    	if(selectedCount == 0){
    		cceaf.util.ExtHelper.showInfoDialog('请选择查看的行');
    	}
    	else if(selectedCount > 1){
    		cceaf.util.ExtHelper.showInfoDialog('只能选择一行查看');
    	}
    	else{
    		//得到编辑对象的主键
    		var masterkeys = treePanel.masterKeyIds.split(',');
    		var url = treePanel.findByKeyAction + '?';
    		var temp = selModel.getLastSelected().get(treePanel.modelKey);
    		url += masterkeys[0] + '=' + temp + '&';

			if(treePanel.newFormCreate == true || treePanel.billForm == null){
	    		treePanel.createForm();
	    	}
	    	
			treePanel.billForm.form.reset();
			treePanel.billForm.setReadOnly(true);
			
			var btnSave = treePanel.billForm.down('[itemId=btnSave]');
			if (btnSave) {
				btnSave.setVisible(false);
			}
			
    		new Ext.Window({
	        	title: title,
	        	modal: true,
	        	width: popWindowWidth,
	        	height: popWindowHeight,
	        	autoScroll:true,
	        	closeAction: 'hide',
	        	layout: 'fit',
	        	items: [treePanel.billForm]
		    }).show();
        	
        	//装载对象到表单
        	treePanel.billForm.form.load({
		    	//url: treePanel.findByKeyAction + '?' + treePanel.masterKeyId + '=' + masterkey,
		    	url:  url,
		        waitMsg : '正在载入数据...',
		        success: function(form,action) { 
		        	//表单载入数据时,设置特殊值
		        	controller.initEditPage(action);
        			
		        	//显示正确提示
		        	var jsonObject =eval("(" + action.response.responseText + ")");
		        	cceaf.util.ExtHelper.showInfoDialog(jsonObject.message);
		        },
		        failure: function(form,action) {
		        	//显示错误提示
		        	var jsonObject =eval("(" + action.response.responseText + ")");
		        	cceaf.util.ExtHelper.showErrorDialog(jsonObject.message);
		        }
		   	});
    	}
    },
    
    /**
     * 删除后操作，默认为调用页面上的itemId=btnQuery按钮单击事件
     * 此方法可在子类重载
     */
    afterDelete: function() {
    	var controller = this;
    	var treePanel = controller.getControlledView();
    	
		var btnQuery = treePanel.up().down('#btnQuery');
		if(btnQuery) {
			btnQuery.fireEvent('click');
		} 
    },
    
    /**
     * 删除对象
     */
    page_delete: function(){
    	var controller = this;
    	var treePanel = controller.getControlledView();
    	
    	//获取要删除对象的主键集
    	var selModel = treePanel.getSelectionModel();
    	var selectedCount = selModel.getCount();
    	if(selectedCount == 0){
    		cceaf.util.ExtHelper.showInfoDialog('请选择要删除的行');
    		return;
    	}
    	else{
    		//确定要删除对象
    		Ext.MessageBox.show({
				title:'确认提示框',
				modal: true,
				msg: '此操作不能回退，确信要删除您选中的对象以及它的子对象吗？',
				minWidth: 200,
				buttons: Ext.MessageBox.YESNO,
				icon: Ext.MessageBox.QUESTION,
				fn:function(btn){
					if(btn == 'yes'){
						//得到删除对象的主键集
						var masterkeys = treePanel.masterKeyIds.split(',');
						var params = {};
						var ids = "";
						for(var j=0;selModel.getSelection() != null && j<selModel.getSelection().length;j++){
				    		var selection = selModel.getSelection()[j];
				    		ids = ids + selection.get(treePanel.modelKey) + ",";
				    	}
						
			    		eval("params." + masterkeys[0] + "s = '" + ids + "';");
						
						//alert(params);
						
			    		Ext.MessageBox.wait('正在处理数据...', '提示'); //进度条等待
			    		Ext.Ajax.request({
			   				url:  treePanel.deleteAction,
			   				//params: { ids: ids },
			   				params: params,
			   				success: function(response){
			   					var isProcessSucess = cceaf.util.ExtHelper.processAjaxRequest(response,true);
			   					if(isProcessSucess){
			   						//删除成功后重新载入treestore
			   						treePanel.getStore().load();
			   						
			   						//删除后的操作，可在子类重载该方法
			   						controller.afterDelete();
			   						
			   					}
			   				},
			   				failure: function(response){
			   					cceaf.util.ExtHelper.processAjaxRequest(response,false);
			   				}
						});
					}
				}
			});
    	}
    },
    
    /**
     * 页面载入时调用
     */
    initPage: function(){
//    	var treePanel = this.getControlledView();
//    	if (!treePanel) {
//    		cceaf.util.ExtHelper.showInfoDialog('controller必须实现getPanelView方法！');
//    		return;
//    	}
    },
    
    /**
     * 新增表单，设置初始值
     */
    initAddPage: function(){
    	
    },
    
    /**
     * 弹出新增窗口前校验，false不弹出新增窗口
     * 
     * @return {Boolean} 校验成功返回true
     */
    checkAddPage: function(){
    	return true;
    },
    
    /**
     * 表单载入数据后,设置特殊值表单值
     */
    initEditPage: function(){
    	
    }
    
});